package com.atguigu.myjuc.demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


//Sysnchronized和Lockd的区别
public class SyncVSLockDemo {
    //资源类
    public synchronized void m1(){
        System.out.println(Thread.currentThread().getName() + "\t" + "----come in");
        try {
            TimeUnit.SECONDS.sleep(4);//新的睡觉 有时分秒毫秒...更方便
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private final Lock lock = new ReentrantLock();
    public void m2() {

        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "----come in");
                try {
                    TimeUnit.SECONDS.sleep(3);//睡一会
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "\t" + "没抢着失败了");
        }
    }
//前面两个都太死板，再写一个时间的 （超过几秒再失效）
    private void m3() {
        try {
            if (lock.tryLock(2L,TimeUnit.SECONDS)){
                try {
                    System.out.println(Thread.currentThread().getName() + "\t" + "----come in");
                    //ting停几秒
                    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
                }finally {
                    lock.unlock();
                }
            }else {
                System.out.println(Thread.currentThread().getName() + "\t" + "----超过2秒抢锁失败，请重试");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) {
        SyncVSLockDemo syncVSLockDemo = new SyncVSLockDemo();

        new Thread(()-> {syncVSLockDemo.m3();},"t1").start();
        new Thread(()-> {syncVSLockDemo.m3();},"t2").start();
    }
}
